﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ProxyWrapper.UserProxy;
using System.Text;
public partial class UserManagement : System.Web.UI.Page
{
    public string messagetype = "";
    public string message = "";

    public ProxyWrapper.UserProxy.UserDetails UserObject { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (Session["userObject"] == null)
            {
                Response.Redirect("Default.aspx", false);
            }
            else
            {
                UserObject = ((ProxyWrapper.UserProxy.UserDetails)Session["UserObject"]);
                if (Request.QueryString["mode"] != null)
                {
                    UpdateData();
                }
                if(Request.QueryString["delcid"]!=null )
                {
                    DeleteComment(Request.QueryString["delcid"].ToString());
                }
                ProxyWrapper.UserServiceWrapper _usr = new ProxyWrapper.UserServiceWrapper();
                DataSet ds = _usr.GetAccountUsers("0");
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {

                }

                DataTable Data = new DataTable();
                if (Request.Form["query"] != null)
                {
                    string search = Request.Form["query"].ToString();
                    DataTable dtFiltered = ds.Tables[0].AsEnumerable().Where(m => m.Field<string>("AppUserName").Contains(search) || m.Field<string>("EmailAddress").Contains(search)).OrderByDescending(m => m.Field<int>("UserId")).CopyToDataTable();
                    lstUsers.DataSource = dtFiltered;
                    lstUsers.DataBind();
                }
                else
                {
                    lstUsers.DataSource = ds;
                    lstUsers.DataBind();
                }
                if (Request.QueryString["action"] != null && Request.QueryString["token"] != null && Request.QueryString["id"] != null)
                {
                    int userId = Convert.ToInt32(Request.QueryString["id"].ToString());
                    ProxyWrapper.UserServiceWrapper _wrap = new ProxyWrapper.UserServiceWrapper();
                    string result = _wrap.DeleteUser(userId, UserObject.ClientId, UserObject.HashCode);
                    if (result.Equals("0"))
                    {
                        messagetype = "S";
                        message = "User " + Request.QueryString["username"].ToString() + " deleted successfully";
                    }
                    else
                    {
                        message = "Error while deleting user" + Request.QueryString["username"].ToString();
                        messagetype = "E";
                    }
                }

            }
        }
        catch (Exception ex)
        { }
    }
    private void UpdateData()
    {
        try
        {
            string userId = Request.Form["userid"].ToString();
            string username = Request.Form["username1"].ToString();

            string fname = Request.Form["fname"] != null ? Request.Form["fname"].ToString() : "";
            string lname = Request.Form["lname"] != null ? Request.Form["lname"].ToString() : "";
            string phone = Request.Form["phone"] != null ? Request.Form["phone"].ToString() : "";
            string password = Request.Form["password"].ToString();
            string email = Request.Form["email"] != null ? Request.Form["email"].ToString() : "";
            string expiry = Request.Form["ed"] != null ? Request.Form["ed"].ToString() : "";
            string userCounts = Request.Form["deviceLimit"].ToString();
            string roleId = Request.Form["roleId"].ToString();
            if (roleId.Equals("2"))
                username = Request.Form["username"] != null ? Request.Form["username"].ToString() : "";

            UserDetails objUser = new UserDetails()
            {
                UserId = Convert.ToInt32(userId),
                UserName = username,
                FirstName = fname,
                LastName = lname,
                PhoneNumber = phone,
                Password = password,
                EmailId = email,
                RoleId = Convert.ToInt32(roleId),
                AccountExpiry = !string.IsNullOrWhiteSpace(expiry) ? Convert.ToDateTime(expiry) : DateTime.Now,
                DeviceLimit = !string.IsNullOrWhiteSpace(userCounts) ? Convert.ToInt32(userCounts) : 0
            };
            ProxyWrapper.UserServiceWrapper _wrapper = new ProxyWrapper.UserServiceWrapper();
            message = _wrapper.UpdateAccounts(objUser);
            messagetype = "S";
            if (objUser.RoleId > 1)
                Response.Redirect("Employee.aspx?msg=" + message, false);
        }
        catch (Exception ex)
        {
        }
    }
    public string GetMessage()
    {
        string warning = "<div class='warning'><p></p><li>{0}</li><p></p></div>";
        string result = "<div class='success'><p></p><li>{0}</li><p></p></div>";
        if (messagetype == "E")
            return string.Format(warning, message);
        else if (messagetype == "S")
            return string.Format(result, message);
        else
            return "";

    }

    private void DeleteComment(string commentId)
    {
        int cid = 0;
        if(Int32.TryParse(commentId,out cid) && cid>0)
        {
            ProxyWrapper.UserServiceWrapper _wrap = new ProxyWrapper.UserServiceWrapper();
            string msg = _wrap.DeleteComments(cid);
            message = msg;
            if (msg.ToLower().Contains("error"))
                messagetype = "E";
            else
                messagetype = "S";
        }
    }
    public string GetComments(string userId,string userName)
    {
        StringBuilder sb = new StringBuilder();
        ProxyWrapper.UserServiceWrapper _wrap = new ProxyWrapper.UserServiceWrapper();
        DataSet ds = _wrap.GetComments(Convert.ToInt32(userId));
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            sb.Append("<br/>");
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sb.Append((i+1).ToString() +". "+ ds.Tables[0].Rows[i]["CommentDesc"].ToString() + ". ");
                sb.Append(" <i style='font-size:15px;font-weight:bold'>Added By: " + ds.Tables[0].Rows[i]["AppUserName"].ToString());
                sb.Append(", Added On: " + ds.Tables[0].Rows[i]["CommentDate"].ToString() + " UTC </i>  ");
                if (UserObject.RoleId == 1)
                {
                    sb.Append("&nbsp;&nbsp; <a href='#' onclick='OpenPage(\"Comments.aspx?edit&addedOnId=" + userId + "&commentid=" + ds.Tables[0].Rows[i]["CommentId"].ToString() + "&username=" + userName + "\")'> Edit</a>");
                    sb.Append(" | <a href='UserManagement.aspx?edit&addedOnId=" + userId + "&delcid=" + ds.Tables[0].Rows[i]["CommentId"].ToString() + "&username=" + userName +")'> Delete</a>");
                }
                sb.Append("<br/>");
            }
            sb.Append("<a href='#' onclick='OpenPage(\"Comments.aspx?add&addedOnId=" + userId + "&username=" + userName + "\")'> Add Comments</a>");
            return sb.ToString();
        }
        else
        {
            return "No comment found. <a href='#' onclick='OpenPage(\"Comments.aspx?add&addedOnId=" + userId + "&username=" + userName + "\")'> Add Comments</a>";
            //<a href='window.open('Comments.aspx?add&addedOnId=" + userId + "','_blank','toolbar=no, scrollbars=yes, resizable=no, top=500, left=500, width=400, height=400');'>Add Comments</a>";
        }
    }
}